﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Business.Sequentials;
using NetDon.OA.Data.CollectionClasses;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Data.HelperClasses;
using NetDon.OA.Data.Linq;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.Common;
using NetDon.OA.Interface.Configuration;
using NetDon.OA.Portal.Common;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Shunting
{
    public partial class IssuringOrderEditUserControl : UserControlBase
    {
        #region Properties

        protected Guid Id
        {
            set { ViewState["Id"] = value; }
            get
            {
                if (ViewState["Id"] != null)
                    return ViewState["Id"].ToString().ToGuid();
                return Guid.Empty;
            }
        }


        private IList<IssuingOrderDeliveryData> IssuingOrderDeliveries
        {
            set { ViewState["IssuingOrderDeliveryData"] = value; }
            get
            {
                if (ViewState["IssuingOrderDeliveryData"] != null)
                    return ViewState["IssuingOrderDeliveryData"] as IList<IssuingOrderDeliveryData>;
                return null;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            txtReceivingOrderDateCalendarExtender1.Format = SystemConfiguration.DateFormat;
            //ControlHelper.SetMaskedEditDateFormat(txtScheduleDate_MaskedEditExtender, scheduledDateFormat);

            this.ddlRouteTypeId.Attributes.Add("onchange", "setFocus(this,'{0}')".Formato(this.ddlRouteTypeId.ClientID));
            this.ddlGoodsShippedTypeId.Attributes.Add("onchange", "setFocus(this,'{0}')".Formato(this.ddlGoodsShippedTypeId.ClientID));
            this.ddlCustomer.Attributes.Add("onchange", "setFocus(this,'{0}')".Formato(this.ddlCustomer.ClientID));
            this.ddlCheckoutType.Attributes.Add("onchange", "setFocus(this,'{0}')".Formato(this.ddlCheckoutType.ClientID));

            this.ddlProvince.Attributes.Add("onchange", "setFocus(this,'{0}')".Formato(
                                                                        this.ddlProvince.
                                                                            ClientID));
            if (!IsPostBack)
            {

            }


        }

        private void LoadProvince()
        {
            var shippingService = ServiceContainer.GetService<ILocationService>();
            var provinces = shippingService.GetProvinces();
            var provinceItems = provinces.Select(
                  entity => new ListItem(entity.Name, entity.ProvinceId)).
                  ToArray();

            this.ddlProvince.Items.Clear();
            this.ddlProvince.Items.AddRange(provinceItems);
            this.ddlProvince.Items.Insert(0, new ListItem(EnumUtilities.GetDescription(ListEmptyType.Select), string.Empty));
        }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ObjectDataSourceCustomers.Selecting += (ds, dsArgs) =>
       {
           dsArgs.InputParameters["areaId"] = CurrentApplicationContext.CompanyId.ToString();
       };


        }

        void ClearInitialDropdown()
        {
            this.ddlRouteTypeId.Items.Clear();
            this.ddlCustomer.Items.Clear();
            this.ddlGoodsShippedTypeId.Items.Clear();
            this.ddlEntruckingAddress.Items.Clear();
        }

        void InsertEmptyList()
        {
            ddlCustomer.InsertEmptyItem(ListEmptyType.Select);
        }

        IssuingOrderData CreateEmptyIssuingOrderData()
        {
            var issuingOrderData = new IssuingOrderData { ReceivingOrderDate = DateTime.Today, OrderStatus = OrderStatus.Submitted, OrderCode = GenerateOrderCode() };
            HiddenFieldOrderStatus.Value = OrderStatus.Submitted.ToString();
            IssuingOrderDeliveries = new List<IssuingOrderDeliveryData>();
            return issuingOrderData;
        }

        void CopyIssuingOrderData()
        {
            GenerateOrderCode();
            GenerateTransportationPlanCode();
            this.lblOrdeVolumn.Text = this.lblOrderQuantity.Text = this.lblOrderWeight.Text = string.Empty;
            IssuingOrderDeliveries = new List<IssuingOrderDeliveryData>();
            AddEmptyIssuingOrderDeliveryAndBind();

        }

        public void LoadUserControl(Guid id)
        {
            Id = id;
            IssuingOrderData issuingOrderData;
            InitialBusinessType(Id == Guid.Empty);
            LoadProvince();
            //add
            if (Id == Guid.Empty)
            {

                issuingOrderData = CreateEmptyIssuingOrderData();
                FormPanelIssuringOrderInfo.DataSource = issuingOrderData;
                FormPanelIssuringOrderInfo.DataBind();
                InsertEmptyList();
                this.FormPanelIssuringOrderInfo.Items["orderStatusItem"].Visible = false;
                this.FormPanelIssuringOrderInfo.Items["orderCode"].ColumnSpan = 2;
                this.FormPanelIssuringOrderInfo.Items["orderCode"].Visible = false;
            }
            //modify
            else
            {
                var orderService = ServiceContainer.GetService<IIssuingOrderService>();
                issuingOrderData = orderService.GetIssuingOrder(Id);

                ClearInitialDropdown();
                FormPanelIssuringOrderInfo.DataSource = issuingOrderData;
                FormPanelIssuringOrderInfo.DataBind();

                LoadGoodsShippedTypes(issuingOrderData.CustomerId.Value);
                InsertEmptyList();

                lblBusinessType.Text = EnumUtilities.GetDescription(issuingOrderData.BusinessType);
                ddlCustomer.SelectedValue = issuingOrderData.CustomerId.ToString();
                ddlGoodsShippedTypeId.SelectedValue = issuingOrderData.GoodsShippedTypeId.ToString();
                ddlEntruckingAddress.SelectedValue = issuingOrderData.EntruckingAddress.ToString();
                ddlCheckoutType.SelectedValue = issuingOrderData.CheckoutType.ToString();
                this.ddlProvince.SelectedValue = issuingOrderData.DeliveryProvince;

                ddlRouteTypeId.SelectedValue = issuingOrderData.RouteTypeId.ToString();

                HiddenFieldOrderStatus.Value = issuingOrderData.OrderStatus.ToString();

                IssuingOrderDeliveries = orderService.GetIssuingOrderDeliveryByOrderId(Id).ToList();


            }

            AddEmptyIssuingOrderDeliveryAndBind();
            OrderStatus = issuingOrderData.OrderStatus;

            FormPanelIssuringOrderInfo.Enabled = IsEditable();
            FormPanelIssuingOrderDelivery.Enabled = IsIssuingOrderDeliveryEditable();



        }

        public bool IsEditable()
        {
            if (Page.IsManager()) return true;
            return OrderStatus == OrderStatus.Submitted;
        }

        public bool IsIssuingOrderDeliveryEditable()
        {
            if (string.IsNullOrWhiteSpace(this.ddlProvince.SelectedValue))
                return false;
            return IsEditable() || (OrderStatus == OrderStatus.Shunted);
        }

        private void InitialBusinessType(bool isAdd)
        {
            var currentBusinessType = (CurrentApplicationContext).BusinessType;
            //if (currentBusinessType == BusinessType.All &&  (!radioBusinesTypeB.Checked || !radioBusinesTypeA.Checked))
            //{
            //    radioBusinesTypeA.Checked = true;
            //}
            if (isAdd)
            {
                if (currentBusinessType == BusinessType.All)
                {
                    this.FormPanelIssuringOrderInfo.Visible = FormPanelIssuingOrderDelivery.Visible = false;
                    this.FormPanelBusinessType.Items["FormItemBusinessTypeViewMode"].Visible = false;
                    this.FormPanelBusinessType.Items["FormItemBusinessTypeEditMode"].Visible = true;
                }
                else
                {
                    this.FormPanelIssuringOrderInfo.Visible = FormPanelIssuingOrderDelivery.Visible = true;
                    lblBusinessType.Text = EnumUtilities.GetDescription(currentBusinessType);
                    this.FormPanelBusinessType.Items["FormItemBusinessTypeViewMode"].Visible = true;
                    this.FormPanelBusinessType.Items["FormItemBusinessTypeEditMode"].Visible = false;
                }
            }
            else
            {
                this.FormPanelIssuringOrderInfo.Visible = FormPanelIssuingOrderDelivery.Visible = true;
                this.FormPanelBusinessType.Items["FormItemBusinessTypeViewMode"].Visible = true;
                this.FormPanelBusinessType.Items["FormItemBusinessTypeEditMode"].Visible = false;
            }
        }

        private void AddEmptyIssuingOrderDeliveryAndBind()
        {
            var tempIssuingOrderDeliveries = IssuingOrderDeliveries;
            tempIssuingOrderDeliveries.Add(new IssuingOrderDeliveryData()
                                           {
                                               Id = Guid.NewGuid(),
                                               AreaId = CurrentApplicationContext.CompanyId,
                                               CreateBy = CurrentApplicationContext.UserId,
                                               CreatedDate = DateTime.Now,
                                               LastUpdatedBy = CurrentApplicationContext.UserId,

                                           });
            IssuingOrderDeliveries = tempIssuingOrderDeliveries; //update viewstate
            gridOrderDetailList.DataSource = IssuingOrderDeliveries;
            gridOrderDetailList.DataBind();
        }

        public bool SaveOrder()
        {
            if (ExtractBusinessType() == BusinessType.All)
            {
                Page.Alert("请选择业务类型！");
                return false;
            }
            DateTime receivingOrderDate;
            if (!DateTime.TryParse(this.txtReceivingOrderDate.Text, out receivingOrderDate))
            {
                //Page.Alert("请输入合法的出单日期！");
                return false;
            }


            var service = ServiceContainer.GetService<IIssuingOrderService>();
            if (service.ExistsIssuingOrderByTransportationPlanCode(Id,txtTransportationPlanCode.Text.Trim()))
            {
                Page.Alert("运输计划号不可以重复！");
                return false;
            }
            var order = Id == Guid.Empty ? new IssuingOrderData() : service.GetIssuingOrder(Id);
   
            ExtractIssuingOrderDelivery();
            //check validation 
            if(this.IssuingOrderDeliveries.Count(o=>!string.IsNullOrWhiteSpace(o.DeliveryOrderCode)) <= 0)
            {
                Page.Alert("请至少输入一个交货单！");
                return false;
            }
            foreach (var issuingOrderDeliery in this.IssuingOrderDeliveries)
            {
                if (string.IsNullOrWhiteSpace(issuingOrderDeliery.DeliveryOrderCode)) continue;
                if (string.IsNullOrWhiteSpace(issuingOrderDeliery.DeliveryCity))
                {
                    Page.Alert("请选择送货城市（交货单号{0})！".Formato(issuingOrderDeliery.DeliveryOrderCode));
                    return false;
                }
                if (WebConfig.IsCalculateByWeight(order.GoodsShippedTypeId))
                {
                    if( !issuingOrderDeliery.OrderWeight.HasValue || issuingOrderDeliery.OrderWeight.Value <=0)
                    {
                        Page.Alert("请输入下单重量（交货单号{0})！".Formato(issuingOrderDeliery.DeliveryOrderCode));
                        return false;
                    }
                  
                }
                else
                {
                    if (!issuingOrderDeliery.OrderVolumn.HasValue || issuingOrderDeliery.OrderVolumn.Value <= 0)
                    {
                        Page.Alert("请输入下单材积（交货单号{0})！".Formato(issuingOrderDeliery.DeliveryOrderCode));
                        return false;
                    }
                }
            }

            order.IssuingOrderDeliveryDataList = IssuingOrderDeliveries;
    
            order = ExtractIssuingOrder(order);



            bool result = false;
            result = Id != Guid.Empty ? service.ModifyOrder(order) : service.AddOrder(order);
            if (result)
                Page.Success("保存成功！");
            return result;

        }

        protected void gridIssuingOrderDelivery_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var issuingOrderDeliveryId = (e.Row.DataItem as IssuingOrderDeliveryData).Id.ToString();
                var ddlCity = (e.Row.FindControl("ddlCity") as DropDownList);
                if (ddlCity.Items.Count <= 0)
                {
                    LoadCity(ddlCity);
                }
                ddlCity.SelectedValue = (e.Row.DataItem as IssuingOrderDeliveryData).DeliveryCity;

                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                if (OrderStatus == OrderStatus.Entrucked)
                {
                    btnDelete.Enabled = true;
                }
                if (btnDelete.Enabled)
                {
                    btnDelete.OnClientClick = string.Format("deleteIssuingOrderDeliveryId('{0}');return false;",
                                                            issuingOrderDeliveryId);
                }

                var txtDeliveryOrderCode = (TextBox)e.Row.FindControl("txtDeliveryOrderCode");
                var ddlDeliveryCodeType = (DropDownList)e.Row.FindControl("ddlDeliveryCodeType");
                var txtDeliveryAddress = (TextBox)e.Row.FindControl("txtDeliveryAddress");
                ddlDeliveryCodeType.SelectedValue = (e.Row.DataItem as IssuingOrderDeliveryData).DeliveryOrderType.ToString();
                ddlDeliveryCodeType.Attributes.Remove("onchange");
                //if (IsLastRow(e.Row.RowIndex))
                //{

                ddlDeliveryCodeType.Attributes.Add("onchange",
                                                    "onChangeDeliveryCode(this,'" + txtDeliveryOrderCode.ClientID +
                                                    "'," + e.Row.RowIndex + ");return false;");
                //}
                ddlCity.Attributes.Add("onchange", "onChangeDeliveryCity(this,'" + txtDeliveryAddress.ClientID +
                                                    "'," + e.Row.RowIndex + ");return false;");
            }
        }
        protected void btnIssuingOrderDeliveryDelete_Click(object sender, EventArgs e)
        {
            var issuingOrderDeliveryId = hfdIssuingOrderDeliveryId.Value.ToGuid();
            var issuingOrderDelivery =
                IssuingOrderDeliveries.FirstOrDefault(src => src.Id == issuingOrderDeliveryId);
            if (issuingOrderDelivery != null)
            {
                IssuingOrderDeliveries.Remove(issuingOrderDelivery);
                //delete from database
                var service = ServiceContainer.GetService<IIssuingOrderService>();
                service.RemoveIssuingOrderDelivery(issuingOrderDeliveryId);
            }
            ExtractIssuingOrderDelivery();
            gridOrderDetailList.DataSource = IssuingOrderDeliveries;
            gridOrderDetailList.DataBind();
        }

        private IssuingOrderData ExtractIssuingOrder(IssuingOrderData order)
        {
            DateTime date;

            if (Id == Guid.Empty)
            {
                order.OrderStatus = OrderStatus.Submitted;
                order.CreateBy = CurrentApplicationContext.UserId;
                order.CreatedDate = DateTime.Now;
                order.ShuntingCost = 0;
                order.ActualEntruckingAmount = 1;
                order.IsGoodsJilted = false;
                order.ActualEntruckingUnit = 0;
            }

            order.Id = Id != Guid.Empty ? Id : Guid.NewGuid();
            order.BusinessType = ExtractBusinessType();
            order.OrderCode = txtOrderCode.Text;
            order.CustomerId = ddlCustomer.SelectedValue.ToGuid();
            order.GoodsShippedTypeId = ddlGoodsShippedTypeId.SelectedValue.ToGuid();
            order.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            if (DateTime.TryParse(txtReceivingOrderDate.Text, out date))
                order.ReceivingOrderDate = date;
            order.OrderVehicleNumber = txtOrderVehicleNumber.Text.ToInt32() ?? 0;
            order.TransportationPlanCode = txtTransportationPlanCode.Text.Trim();
            order.DeliveryProvince = this.ddlProvince.SelectedValue;

            order.OrderVolumn = order.IssuingOrderDeliveryDataList.Sum(o => o.OrderVolumn);
            order.OrderWeight = order.IssuingOrderDeliveryDataList.Sum(o => o.OrderWeight);
            order.OrderQuantity = order.IssuingOrderDeliveryDataList.Sum(o => o.OrderQuantity);
            order.UnitCost = order.IssuingOrderDeliveryDataList.Sum(o => o.UnitCost);
            if (order.ShuntingCost <= 0)
            {
                order.ShuntingCost = SystemUtility.GetShuntingCost(order.IssuingOrderDeliveryDataList,
                                                                   WebConfig.IsCalculateByWeight(
                                                                       order.GoodsShippedTypeId));
            }

            order.CheckoutType = EnumUtilities.Parse<CheckoutType>(ddlCheckoutType.SelectedValue);
            order.EntruckingAddress = ddlEntruckingAddress.SelectedValue.ToGuid();
            order.EntruckingDetails = txtEntruckingDetails.Text;
            order.AreaId = (CurrentApplicationContext).CompanyId;
            order.LastUpdatedBy = CurrentApplicationContext.UserId;
            order.LastUpdatedDate = DateTime.Now;

            return order;
        }
        private BusinessType ExtractBusinessType()
        {
            if (this.FormPanelBusinessType.Items["FormItemBusinessTypeViewMode"].Visible)
            {
                return string.IsNullOrWhiteSpace(this.lblBusinessType.Text) ? CurrentApplicationContext.BusinessType : EnumUtilities.Parse<BusinessType>(this.lblBusinessType.Text);
            }
            if (radioBusinesTypeA.Checked)
                return BusinessType.A;
            if (radioBusinesTypeB.Checked)
                return BusinessType.B;
            return BusinessType.All;

        }

        private void ExtractIssuingOrderDelivery()
        {
            var tempIssuingOrderDeliveries = new List<IssuingOrderDeliveryData>();
            foreach (GridViewRow detailRow in gridOrderDetailList.Rows)
            {
                var issuingOrderDeliveryId = gridOrderDetailList.DataKeys[detailRow.RowIndex]["Id"].ToString().ToGuid();
                var issuingOrderDelivery = IssuingOrderDeliveries.FirstOrDefault(src => src.Id == issuingOrderDeliveryId);

                if (issuingOrderDelivery != null)
                {
                    issuingOrderDelivery.IssuingOrderId = Id;
                    issuingOrderDelivery.OrderCode = this.txtOrderCode.Text;
                    issuingOrderDelivery.BusinessType = ExtractBusinessType();
                    issuingOrderDelivery.TransportationPlanCode = this.txtTransportationPlanCode.Text.Trim();
                    issuingOrderDelivery.DeliveryOrderType = (detailRow.FindControl("ddlDeliveryCodeType") as DropDownList).SelectedValue.ToGuid();
                    issuingOrderDelivery.DeliveryOrderCode = (detailRow.FindControl("txtDeliveryOrderCode") as TextBox).Text;
                    issuingOrderDelivery.DeliveryAddress = (detailRow.FindControl("txtDeliveryAddress") as TextBox).Text;
                    issuingOrderDelivery.DeliveryCity = (detailRow.FindControl("ddlCity") as DropDownList).SelectedValue;

                    issuingOrderDelivery.UnitCost = (detailRow.FindControl("txtUnitCost") as TextBox).Text.ToDecimal() ;
                    issuingOrderDelivery.OrderQuantity = (detailRow.FindControl("txtOrderQuantity") as TextBox).Text.ToDecimal() ;
                    issuingOrderDelivery.OrderVolumn = (detailRow.FindControl("txtOrderVolumn") as TextBox).Text.ToDecimal() ;
                    issuingOrderDelivery.OrderWeight =
                        (detailRow.FindControl("txtOrderWeight") as TextBox).Text.ToDecimal();


                    issuingOrderDelivery.LastUpdatedBy = CurrentApplicationContext.UserId;
                    issuingOrderDelivery.CreatedDate = issuingOrderDelivery.LastUpdatedDate = DateTime.Now;
                    tempIssuingOrderDeliveries.Add(issuingOrderDelivery);
                }

            }

            //update viewstate
            IssuingOrderDeliveries = tempIssuingOrderDeliveries;
        }

        protected void DateValidator_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            DateTime value;
            e.IsValid = DateTime.TryParse(e.Value, out value);
        }

        public void ddlCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ddlCustomer.SelectedValue))
            {
                //generate order ode
                if (Id == Guid.Empty)
                {
                    GenerateOrderCode();
                }
                //Load goods ship type
                LoadGoodsShippedTypes(ddlCustomer.SelectedValue.ToGuid());
            }


        }


        private void LoadGoodsShippedTypes(Guid customerId)
        {
            this.ddlGoodsShippedTypeId.Items.Clear();

            var goodsShippedTypeids = ServiceContainer.GetService<ICustomerInfoService>().GetCustomerGoodsShippTypes(
                customerId, CurrentApplicationContext.CompanyId);

            this.ddlGoodsShippedTypeId.DataSource = goodsShippedTypeids;
            this.ddlGoodsShippedTypeId.DataBind(); ;

            ddlGoodsShippedTypeId.InsertEmptyItem(ListEmptyType.Select);
        }

        public void radioBusinesType_CheckedChanged(object sender, EventArgs e)
        {

            this.FormPanelIssuringOrderInfo.Visible = this.FormPanelIssuingOrderDelivery.Visible = true;

        }

        public void ddlGoodsShippedTypeId_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ddlGoodsShippedTypeId.SelectedValue))
            {
                GenerateTransportationPlanCode();
               // GenerateOrderDeliveryCode();
                ChangeOrderVehicleNumber();
            }

        }


        public void ddlCheckoutType_SelectedIndexChanged(object sender, EventArgs e)
        {

            ChangeOrderVehicleNumber();


        }

        void ChangeOrderVehicleNumber()
        {
            if (!string.IsNullOrWhiteSpace(ddlCheckoutType.SelectedValue))
            {
                if (this.ddlCheckoutType.SelectedValue == WebConfig.Whole)
                {
                    this.txtOrderVehicleNumber.Text = "1";
                }
                else if (this.ddlCheckoutType.SelectedValue == WebConfig.LessThanCarLoad)
                {
                    this.txtOrderVehicleNumber.Text = "0";
                }
            }
        }

        bool IsGoodsShippedMadeupPaper()
        {
            return true;
            // return ddlGoodsShippedTypeId.SelectedItem.Text.Trim() == WebConfig.MadeupPaper;
        }
        public void txtDeliveryOrderCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(HiddenDeliveryCode.Value))
            {
                ExtractIssuingOrderDelivery();
            }

            AddEmptyIssuingOrderDeliveryAndBind();
            GenerateOrderDeliveryCode();
        }


        public void txtDeliveryOrderCity_SelectedIndexChanged(object sender, EventArgs e)
        {

            ExtractIssuingOrderDelivery();
            GenerateDeliveryOrderUnitCost();
        }

        public void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ddlProvince.SelectedValue))
            {
                this.FormPanelIssuingOrderDelivery.Enabled = true;
                foreach (GridViewRow detailRow in gridOrderDetailList.Rows)
                {
                    var ddlCity = (detailRow.FindControl("ddlCity") as DropDownList);
                    LoadCity(ddlCity);
                }
            }
        }

        private void LoadCity(DropDownList ddlCity)
        {
            var shippingService = ServiceContainer.GetService<ILocationService>();

            var cities = shippingService.GetCities(ddlProvince.SelectedValue);
            var cityItems =
              cities.Select(
                  entity => new ListItem(entity.Name, entity.CityId)).
                  ToArray();

            ddlCity.Items.Clear();
            ddlCity.Items.AddRange(cityItems);
            ddlCity.Items.Insert(0, new ListItem(EnumUtilities.GetDescription(ListEmptyType.Select), string.Empty));
        }


        void GenerateTransportationPlanCode()
        {
            if (IsGoodsShippedMadeupPaper())
            {
                if (string.IsNullOrWhiteSpace(txtTransportationPlanCode.Text.Trim()))
                {
                    //generate order ode
                    txtTransportationPlanCode.Text =
                        SystemConfiguration.DefaultTransportationPrefix(CurrentApplicationContext.CompanyId);
                }
            }

        }


        void GenerateOrderDeliveryCode()
        {
            if (IsGoodsShippedMadeupPaper())
            {
                bool isChanged = false;
                int i = 0;
                foreach (var issuingOrderDeliveryData in IssuingOrderDeliveries)
                {
                    if (issuingOrderDeliveryData.DeliveryOrderType.HasValue)
                    {

                        if (!string.IsNullOrWhiteSpace(HiddenRowIndex.Value))
                        {
                            if (HiddenRowIndex.Value == i.ToString())
                            {
                                isChanged = true;
                                issuingOrderDeliveryData.DeliveryOrderCode = GetDefaultDeliveryOrderCode(issuingOrderDeliveryData.DeliveryOrderType.Value);
                                break;
                            }
                        }
                        else
                        {
                            isChanged = true;
                            issuingOrderDeliveryData.DeliveryOrderCode = GetDefaultDeliveryOrderCode(issuingOrderDeliveryData.DeliveryOrderType.Value);
                        }


                    }
                    i++;
                }
                if (isChanged)
                {
                    IssuingOrderDeliveries = IssuingOrderDeliveries;
                    gridOrderDetailList.DataSource = IssuingOrderDeliveries;
                    gridOrderDetailList.DataBind();
                }

            }

        }

        void GenerateDeliveryOrderUnitCost()
        {
            int i = 0;
            foreach (var issuingOrderDeliveryData in IssuingOrderDeliveries)
            {
                if (!string.IsNullOrWhiteSpace(HiddenRowIndex.Value))
                {
                    if (HiddenRowIndex.Value == i++.ToString())
                    {
                        var service = ServiceContainer.GetService<IIssuingOrderService>();

                        issuingOrderDeliveryData.UnitCost = service.GetUnitCost(CurrentApplicationContext.CompanyId, issuingOrderDeliveryData.DeliveryCity, this.ddlRouteTypeId.SelectedValue.ToGuid());

                        break;
                    }
                }
            }
            IssuingOrderDeliveries = IssuingOrderDeliveries;
            gridOrderDetailList.DataSource = IssuingOrderDeliveries;
            gridOrderDetailList.DataBind();

        }


        string GetDefaultDeliveryOrderCode(Guid deliveryOrderCodeType)
        {

            var entity = new LinqMetaData().DeliveryOrderCodeConfig.FirstOrDefault(e => e.DeliveryCodeType == deliveryOrderCodeType);
            return entity == null ? string.Empty : entity.DeliveryOrderCodePrefix;

        }
        string GenerateOrderCode()
        {
            if (!string.IsNullOrWhiteSpace(ddlCustomer.SelectedValue))
            {
                this.txtOrderCode.Text = Sequential.Generate(SequentialKeys.CustomerOrderCode,
                                                             new OrderCodeContext
                                                                 {

                                                                     CustomerCode =
                                                                         new CustomerInfoEntity(
                                                                         ddlCustomer.SelectedValue.ToGuid()).
                                                                         CustomerCode
                                                                 }, true);

                
            }
            return this.txtOrderCode.Text;
        }
        internal void LoadNavigationView(Guid id)
        {

            Id = id;
            if (id == Guid.Empty) //A类成品纸
            {
                radioBusinesType_CheckedChanged(null, null);
                if (IsGoodsShippedMadeupPaper())
                {
                    CopyIssuingOrderData();
                }

            }
            else
            {
                LoadUserControl(id);
            }
        }
    }
}